var maps = {};
var markers = {};

var popover_options = {
    trigger: 'hover',
    placement: 'top',
    container: 'body',
    html: true,
    selector: '[rel="popover"]', //Sepcify the selector here
    content: function () {
        return $('#popover-content').html();
    }
};

var ckeditor_options = {
    toolbarGroups: [
        {name: 'clipboard'},
        {name: 'editing'},
        {name: 'basicstyles'},
        {name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ]},
        {items: [ 'Table', 'HorizontalRule', 'SpecialChar' ]},
        {name: 'styles'},
        {items: [ 'TextColor' ]},
        {name: 'tools'},
        {name: 'others', items: [ '-' ]},
    ]
};

// ----------------------------------------------------------------------------- Text Functions
function reset_text_form() {
    $('#text_data_types').show();
    
    $('#text_db_type option.text').hide();
    $('#text_db_type option.numeric').hide();

    $('#text_type_container').show();

    $('#text_numeric').prop('checked', false);
    $('#text_valid_email').prop('checked', false);
    $('#text_valid_url').prop('checked', false);

    $('#text_numeric').prop('disabled', true);
    $('#text_valid_email').prop('disabled', true);
    $('#text_valid_url').prop('disabled', true);

    $('#text_icon').prop('checked', true);

    $('#text_min_length').val(2);
    $('#text_max_length').val(1000);
    
    $('#text_db_type').val('varchar');
    $('#text_confirm_password').slideUp();
    
    $('#text_use_spinner').slideUp();
    $('#text_spinner').val('');
}

function to_text_input() {
    $('#text_modal_title').text('Text Input');
    $('#text_save_btn').text('Create Text Input');

    $('#text_type').val('text');
    $('#text_db_type option.text').show();
    
    $('#text_label').prop('placeholder', 'Title');
    $('#text_name').prop('placeholder', 'title');
    $('#text_id').prop('placeholder', 'title');
    $('#text_placeholder').prop('placeholder', 'Title');
    $('#text_initial_value').prop('placeholder', 'Title');
    $('#text_initial_value').val('');
}

function to_password_input() {
    $('#text_modal_title').text('Password Input');
    $('#text_save_btn').text('Create Password Input');

    $('#text_type').val('password');
    $('#text_confirm_password').slideDown();
    $('#text_db_type option.text').show();
    
    $('#text_label').prop('placeholder', 'Password');
    $('#text_name').prop('placeholder', 'Password');
    $('#text_id').prop('placeholder', 'Password');
    $('#text_placeholder').prop('placeholder', 'P4s5w0rd');
    $('#text_initial_value').prop('placeholder', 'P4s5w0rd');
    $('#text_initial_value').val('');
}

function to_email_input() {
    $('#text_modal_title').text('Email Input');
    $('#text_save_btn').text('Create Email Input');

    $('#text_type').val('email');
    $('#text_valid_email').prop('disabled', false);
    $('#text_valid_email').prop('checked', 'checked');

    $('#text_db_type option.text').show();
    
    $('#text_label').prop('placeholder', 'Email');
    $('#text_name').prop('placeholder', 'email');
    $('#text_id').prop('placeholder', 'email');
    $('#text_placeholder').prop('placeholder', 'sample@email.com');
    $('#text_initial_value').prop('placeholder', 'sample@email.com');
    $('#text_initial_value').val('');
}

function to_number_input() {
    $('#text_modal_title').text('Number Input');
    $('#text_save_btn').text('Create Number Input');
    
    $('#text_type').val('number');
    $('#text_numeric').prop('checked', 'checked');
    $('#text_numeric').prop('disabled', false);
    $('#text_db_type').val('int');

    $('#text_min_length').val(1);
    $('#text_max_length').val(10);
    
    $('#text_use_spinner').slideDown();
    $('#text_db_type option.numeric').show();
    $('#text_int').prop('checked', true);
    
    $('#text_label').prop('placeholder', 'Price');
    $('#text_name').prop('placeholder', 'price');
    $('#text_id').prop('placeholder', 'price');
    $('#text_placeholder').prop('placeholder', '20.50');
    $('#text_initial_value').prop('placeholder', '0');
    $('#text_initial_value').val('0');
}

function to_url_input() {
    $('#text_modal_title').text('URL Input');
    $('#text_save_btn').text('Create URL Input');

    $('#text_type').val('url');
    $('#text_valid_url').prop('disabled', false);
    $('#text_valid_url').prop('checked', 'checked');

    $('#text_db_type option.text').show();
    
    $('#text_label').prop('placeholder', 'URL');
    $('#text_name').prop('placeholder', 'url');
    $('#text_id').prop('placeholder', 'url');
    $('#text_placeholder').prop('placeholder', 'http://www.domain_name.com');
    $('#text_initial_value').prop('placeholder', 'http://www.domain_name.com');
    $('#text_initial_value').val('');
}

// ----------------------------------------------------------------------------- Textarea Functions
function reset_textarea_form() {
    to_textarea_textarea();
    
    $('#textarea_label').val('');
    $('#textarea_name').val('');
    $('#textarea_id').val('');
    $('#textarea_placeholder').val('');
    
    $('#textarea_type_container').show();
}

function to_textarea_textarea() {
    $('#textarea_modal_title').text('Textarea');
    $('#textarea_save_btn').text('Create Textarea');
    
    $('#textarea_type').val('textarea');
}

function to_textarea_wysiwyg() {
    $('#textarea_modal_title').text('WYSIWYG');
    $('#textarea_save_btn').text('Create WYSIWYG');
    
    $('#textarea_type').val('wysiwyg');
}

// ----------------------------------------------------------------------------- Datetime Functions
function reset_datetime_form() {
    to_datetime_datetime();
    
    $('#datetime_label').val('');
    $('#datetime_name').val('');
    $('#datetime_id').val('');
    
    $('#datetime_type_container').show();
}

function to_datetime_time() {
    $('#datetime_modal_title').text('Time Input');
    $('#datetime_save_btn').text('Create Time Input');
    
    $('#datetime_type').val('time');
    $('#datetime_db_type').val('time');
    
    $('#datetime_db_type option.time').show();
    $('#datetime_db_type option.date').hide();
    $('#datetime_db_type option.datetime').show();
    
    $('#datetime_initial_value_dropdown_container').slideUp();
    $('#datetime_initial_value_container').slideDown();

    $('#datetime_label').prop('placeholder', 'Time');
    $('#datetime_name').prop('placeholder', 'time');
    $('#datetime_id').prop('placeholder', 'time');
    $('#datetime_placeholder').prop('value', '10:30 AM');
    $('#datetime_placeholder').prop('placeholder', '10:30 AM');
    $('#datetime_initial_value').prop('placeholder', '10:30 AM');
}

function to_datetime_date() {
    $('#datetime_modal_title').text('Date Input');
    $('#datetime_save_btn').text('Create Date Input');
    
    $('#datetime_type').val('date');
    $('#datetime_db_type').val('date');
    
    $('#datetime_db_type option.time').hide();
    $('#datetime_db_type option.date').show();
    $('#datetime_db_type option.datetime').show();
    
    $('#datetime_initial_value_dropdown_container').slideUp();
    $('#datetime_initial_value_container').slideDown();
    
    $('#datetime_label').prop('placeholder', 'Date');
    $('#datetime_name').prop('placeholder', 'date');
    $('#datetime_id').prop('placeholder', 'date');
    $('#datetime_placeholder').prop('value', '03/14/1989');
    $('#datetime_placeholder').prop('placeholder', '03/14/1989');
    $('#datetime_initial_value').prop('placeholder', '03/14/1989');
}

function to_datetime_date_range() {
    $('#datetime_modal_title').text('Date Range Input');
    $('#datetime_save_btn').text('Create Date Range Input');
    
    $('#datetime_type').val('daterange');
    $('#datetime_db_type').val('date');
    
    $('#datetime_db_type option.time').hide();
    $('#datetime_db_type option.date').show();
    $('#datetime_db_type option.datetime').show();
    
    $('#datetime_initial_value_dropdown_container').slideUp();
    $('#datetime_initial_value_container').slideDown();
    
    $('#datetime_label').prop('placeholder', 'Date Range');
    $('#datetime_name').prop('placeholder', 'date range');
    $('#datetime_id').prop('placeholder', 'date range');
    $('#datetime_placeholder').prop('value', '03/14/1989 - 03/14/2014');
    $('#datetime_placeholder').prop('placeholder', '03/14/1989 - 03/14/2014');
    $('#datetime_initial_value').prop('placeholder', '03/14/1989 - 03/14/2014');
}

function to_datetime_datetime() {
    $('#datetime_modal_title').text('Datetime Input');
    $('#datetime_save_btn').text('Create Datetime Input');
    
    $('#datetime_type').val('datetime');
    $('#datetime_db_type').val('datetime');
    
    $('#datetime_db_type option.time').hide();
    $('#datetime_db_type option.date').hide();
    $('#datetime_db_type option.datetime').show();
    
    $('#datetime_initial_value_dropdown_container').slideUp();
    $('#datetime_initial_value_container').slideDown();
    
    $('#datetime_label').prop('placeholder', 'Datetime');
    $('#datetime_name').prop('placeholder', 'datetime');
    $('#datetime_id').prop('placeholder', 'datetime');
    $('#datetime_placeholder').prop('value', '03/14/1989 10:30:00 AM');
    $('#datetime_placeholder').prop('placeholder', '03/14/1989 10:30:00 AM');
    $('#datetime_initial_value').prop('placeholder', '03/14/1989 10:30:00 AM');
}

function to_datetime_datetime_range() {
    $('#datetime_modal_title').text('Datetime Range Input');
    $('#datetime_save_btn').text('Create Datetime Range Input');
    
    $('#datetime_type').val('datetimerange');
    $('#datetime_db_type').val('datetime');
    
    $('#datetime_db_type option.time').hide();
    $('#datetime_db_type option.date').hide();
    $('#datetime_db_type option.datetime').show();
    
    $('#datetime_initial_value_dropdown_container').slideUp();
    $('#datetime_initial_value_container').slideDown();
    
    $('#datetime_label').prop('placeholder', 'Datetime Range');
    $('#datetime_name').prop('placeholder', 'datetime range');
    $('#datetime_id').prop('placeholder', 'datetime range');
    $('#datetime_placeholder').prop('value', '03/14/1989 10:30 AM - 03/14/2014 10:30 PM');
    $('#datetime_placeholder').prop('placeholder', '03/14/1989 10:30 AM - 03/14/2014 10:30 PM');
    $('#datetime_initial_value').prop('placeholder', '03/14/1989 10:30 AM - 03/14/2014 10:30 PM');
}

function to_datetime_timezone() {
    $('#datetime_modal_title').text('Timezone Input');
    $('#datetime_save_btn').text('Create Timezone Input');
    
    $('#datetime_type').val('timezone');
    $('#datetime_db_type').val('datetime');
    
    $('#datetime_db_type option.time').hide();
    $('#datetime_db_type option.date').hide();
    $('#datetime_db_type option.datetime').hide();
    $('#datetime_db_type option.timezone').show();
    
    $('#datetime_initial_value_dropdown_container').slideDown();
    $('#datetime_initial_value_container').slideUp();
    
    $('#datetime_label').prop('placeholder', 'Timezone');
    $('#datetime_name').prop('placeholder', 'timezone');
    $('#datetime_id').prop('placeholder', 'timezone');
}

// ----------------------------------------------------------------------------- File Upload Functions
function reset_upload_form() {
    to_upload_file();
    
    $('#upload_label').val('');
    $('#upload_name').val('');
    $('#upload_id').val('');
    $('#upload_location').val('uploads/images/folder_name');
    
    $('#upload_resize').prop('checked', false);
    $('#upload_width').val('');
    $('#upload_height').val('');
    
    $('#upload_type_container').show();
    $('#upload_resize_container').hide();
    $('#upload_width_container').hide();
    $('#upload_height_container').hide();
}

function to_upload_file() {
    $('#upload_modal_title').text('File Uploader');
    $('#upload_save_btn').text('Create File Uploader');

    $('#upload_type').val('upload_file');
    
    $('#upload_label').prop('placeholder', 'File');
    $('#upload_name').prop('placeholder', 'file');
    $('#upload_id').prop('placeholder', 'file');
    
    $('#upload_resize').prop('checked', false);
    $('#upload_width').val('');
    $('#upload_height').val('');
    
    $('#upload_resize_container').hide();
    $('#upload_width_container').hide();
    $('#upload_height_container').hide();
}

function to_upload_multiple() {
    $('#upload_modal_title').text('Multiple File Uploader');
    $('#upload_save_btn').text('Create Multiple File Uploader');
    
    $('#upload_type').val('upload_multiple');
    
    $('#upload_label').prop('placeholder', 'File');
    $('#upload_name').prop('placeholder', 'file');
    $('#upload_id').prop('placeholder', 'file');
    
    $('#upload_resize').prop('checked', true);
    $('#upload_width').val('');
    $('#upload_height').val('');
    
    $('#upload_resize_container').show();
    $('#upload_width_container').show();
    $('#upload_height_container').show();
}

function to_upload_image() {
    $('#upload_modal_title').text('Image Uploader');
    $('#upload_save_btn').text('Create Image Uploader');
    
    $('#upload_type').val('upload_image');
    
    $('#upload_label').prop('placeholder', 'Image');
    $('#upload_name').prop('placeholder', 'image');
    $('#upload_id').prop('placeholder', 'image');
    
    $('#upload_resize').prop('checked', true);
    $('#upload_width').val('');
    $('#upload_height').val('');
    
    $('#upload_resize_container').show();
    $('#upload_width_container').show();
    $('#upload_height_container').show();
}

function to_upload_url() {
    $('#upload_modal_title').text('URL or Image Uploader');
    $('#upload_save_btn').text('Create URL or Image Uploader');
    
    $('#upload_type').val('upload_url');
    
    $('#upload_label').prop('placeholder', 'Image');
    $('#upload_name').prop('placeholder', 'image');
    $('#upload_id').prop('placeholder', 'image');
    
    $('#upload_resize').prop('checked', true);
    $('#upload_width').val('');
    $('#upload_height').val('');
    
    $('#upload_resize_container').show();
    $('#upload_width_container').show();
    $('#upload_height_container').show();
}

function url_to_upload(selector)
{
    $('#' + selector + '_file_container').hide();
    $('#' + selector + '_url_check').prop('checked', true);
    $('#' + selector + "_radio_container input:radio").change(function() {
        var value = $(this).val();
        if (value === 'url')
        {
            $('#' + selector + '_url_container').slideDown();
            $('#' + selector + '_file_container').slideUp();
        } else
        {
            $('#' + selector + '_url_container').slideUp();
            $('#' + selector + '_file_container').slideDown();
        }
    });
}

// ----------------------------------------------------------------------------- Color Picker Functions
function reset_color_form() {
    $('#color_label').val('');
    $('#color_name').val('');
    $('#color_id').val('');
    $('#color_placeholder').val('#ffffff');
    $('#color_initial_value').val('#ffffff');
    $('#color_format').val('hex');
    
    $('#color_icon').prop('checked', true);
}

// ----------------------------------------------------------------------------- Geolocation Functions
function reset_geolocation_form() {
    $('#geolocation_label').val('');
    $('#geolocation_name').val('');
    $('#geolocation_id').val('');
    $('#geolocation_placeholder').val('');
    
    $('#geolocation_icon').prop('checked', true);
}

// ----------------------------------------------------------------------------- Toggle Functions
function reset_toggle_form() {
    $('#toggle_label').val('');
    $('#toggle_name').val('');
    $('#toggle_id').val('');
    
    $('#switch').prop('checked', false);
    
    $('#switch_on_container').hide();
    $('#switch_off_container').hide();
    
    $('#toggle_modal_title').text('Toggle');
    $('#toggle_save_btn').text('Create Toggle Input');
}

function to_switch() {
    $('#toggle_label').val('');
    $('#toggle_name').val('');
    $('#toggle_id').val('');
    
    $('#switch').prop('checked', true);
    
    $('#switch_on_container').show();
    $('#switch_off_container').show();
    
    $('#toggle_modal_title').text('Switch');
    $('#toggle_save_btn').text('Create Switch');
}

// ----------------------------------------------------------------------------- Captcha Functions
function reset_captcha_form() {
    $('#captcha_label').val('');
    $('#captcha_name').val('');
    $('#captcha_id').val('');
    $('#captcha_placeholder').val('Type what you see above');
    
    $('#switch').prop('checked', false);
    
    $('#switch_on_container').hide();
    $('#switch_off_container').hide();
    
    $('#toggle_modal_title').text('Toggle');
    $('#toggle_save_btn').text('Create Toggle Input');
}

// ----------------------------------------------------------------------------- Single Functions
function reset_single_form() {
    $('#single_label').val('');
    $('#single_name').val('');
    $('#single_id').val('');
    $('#single_type').val('dropdown');
    $('#single_data').val('custom');
    
    $('#single_with_search').prop('checked', false);
    
    $('#single_with_image_container').show();
    $('#single_with_image').prop('checked', false);
    $('.has-image').hide();

    // database data
    $('#single_db_table_name_container').hide();
    $('#single_db_table_value_container').hide();
    $('#single_db_table_text_container').hide();
    $('#single_db_table_image_container').hide();
    
    $('#single_db_foreign_key_container').hide();
    $('#single_db_plural_container').hide();
    $('#single_db_singular_container').hide();
    
    $('#single_modal_title').text('Dropdown Menu');
    $('#single_save_btn').text('Create Dropdown Menu');
    
    $('#single_selected_text').prop('placeholder', 'Option Default Text');
    $('#single_selected_value').prop('placeholder', 'Option Default Value');
    
    $('#single_type_container').show();
    
    $('#single_data').val('custom');
}

function to_single_dropdown() {
    
    $('#single_modal_title').text('Dropdown Menu');
    $('#single_save_btn').text('Create Dropdown Menu');
    
    $('#single_type').val('dropdown');
    
    $('#single_with_image_container').show();
    $('#single_with_image').prop('checked', false);
    $('.has-image').hide();
    
    $('#single_selected_text').prop('placeholder', 'Option Default Text');
    $('#single_selected_value').prop('placeholder', 'Option Default Value');
    
    $('#single_with_search_container').show();
}

function to_single_radio() {
    
    $('#single_modal_title').text('Radio Buttons');
    $('#single_save_btn').text('Create Radio Buttons');
    
    $('#single_type').val('radio');
    
    $('#single_with_image_container').hide();
    $('#single_with_image').prop('checked', false);
    $('.has-image').hide();
    
    $('#single_selected_text').prop('placeholder', 'Radio Default Text');
    $('#single_selected_value').prop('placeholder', 'Radio Default Value');
    
    $('#single_with_search_container').hide();
}

function create_single_data() {
    
    $('#single_custom_data_container div.data input.value').off();
    $('#single_custom_data_container div.data input.value').change(function(e) {
        e.preventDefault();
        var text_equiv = $(this).parent().find('input.text');
        text_equiv.val( $(this).val().toLowerCase().replace(/ /g,'_') );
    });
    
    $('#single_custom_data_container div.data a.btn_add').off();
    $('#single_custom_data_container div.data a.btn_add').click(function(e) {
        e.preventDefault();
        
        var data_option = $(this).parent();
        var markup = '';
        
        var image_path = $('#single_image_path').val();
        
        markup += '<div class="data">\n';
        markup += '<input type="text" name="data[][text]" class="value input-xlarge" data-rule-required="true" data-rule-minlength="1" placeholder="Text" value="">\n';
        markup += '<input type="text" name="data[][value]" class="text input-xlarge" data-rule-required="true" data-rule-minlength="1" placeholder="Value" value="">\n';
        markup += '<input type="text" id="single_selected_image" name="data[][image]" class="image input-xlarge has-image" data-rule-required="true" data-rule-minlength="1" placeholder="URL or path" value="' +image_path+ '">\n';
        markup += '<a href="javascript:void(0)" class="btn btn-mini btn_add" rel="tooltip" title="Add Data Below"><i class="icon-plus"></i></a>\n';
        markup += '<a href="javascript:void(0)" class="btn btn-mini btn_delete" rel="tooltip" title="Delete This Data"><i class="icon-minus"></i></a>\n';
        markup += '</div>';
        
        data_option.after(markup);
        
        $('#single_custom_data_container div.data a.btn_delete').click(function(e) {
            var to_be_removed = $(this).parent();
            to_be_removed.remove();
        });
        
        create_single_data();
        
        if( ! $('#single_with_image').prop('checked') ) {
            $('.has-image').hide();
        }
        
    });
}

// ----------------------------------------------------------------------------- Multiple Functions
function reset_multiple_form() {
    $('#multiple_label').val('');
    $('#multiple_name').val('');
    $('#multiple_id').val('');
    $('#multiple_type').val('multiple_dropdown');
    $('#multiple_data').val('custom');

    $('#multiple_default_values_container').hide();
    
    $('#multiple_with_image_container').show();
    $('#multiple_with_image').prop('checked', false);
    $('.multiple-has-image').hide();

    // database data
    $('#multiple_db_table_name_container').hide();
    $('#multiple_db_table_value_container').hide();
    $('#multiple_db_table_text_container').hide();
    
    $('#multiple_db_foreign_key_container').hide();
    $('#multiple_db_plural_container').hide();
    $('#multiple_db_singular_container').hide();
    
    $('#multiple_modal_title').text('Dropdown Menu');
    $('#multiple_save_btn').text('Create Dropdown Menu');
    
    $('#multiple_selected_text').prop('placeholder', 'Option Default Text');
    $('#multiple_selected_value').prop('placeholder', 'Option Default Value');
    
    $('#multiple_type_container').show();
    $('#multiple_type').val('multiple_dropdown');
    
    $('#multiple_data').val('custom');
}

function to_multiple_dropdown() {
    
    $('#multiple_modal_title').text('Dropdown Menu');
    $('#multiple_save_btn').text('Create Dropdown Menu');
    
    $('#multiple_type').val('multiple_dropdown');
    
    $('#multiple_with_image_container').show();
    $('#multiple_with_image').prop('checked', false);
    $('.multiple-has-image').hide();
    
    $('#multiple_default_values_container').hide();
    $('#multiple_data_container').show();
    $('#multiple_custom_data_container').show();
    
    $('#multiple_selected_text').prop('placeholder', 'Option Default Text');
    $('#multiple_selected_value').prop('placeholder', 'Option Default Value');
    
    $('#multiple_with_search_container').show();
}

function to_multiple_checkbox() {
    
    $('#multiple_modal_title').text('Checkbox');
    $('#multiple_save_btn').text('Create Checkbox');
    
    $('#multiple_type').val('checkbox');
    
    $('#multiple_default_values_container').hide();
    $('#multiple_data_container').show();
    $('#multiple_custom_data_container').show();
    
    $('#multiple_with_image_container').hide();
    $('#multiple_with_image').prop('checked', false);
    $('.multiple-has-image').hide();
    
    $('#multiple_selected_text').prop('placeholder', 'Checkbox Default Text');
    $('#multiple_selected_value').prop('placeholder', 'Checkbox Default Value');
    
    $('#multiple_with_search_container').hide();
}

function to_multiple_tagsinput() {
    
    $('#multiple_modal_title').text('Tagsinput');
    $('#multiple_save_btn').text('Create Tagsinput');
    
    $('#multiple_type').val('tagsinput');
    
    $('#multiple_default_values_container').show();
    $('#multiple_data_container').hide();
    $('#multiple_custom_data_container').hide();
    
    $('#multiple_with_image_container').hide();
    $('#multiple_with_image').prop('checked', false);
    $('.multiple-has-image').hide();
    
    $('#multiple_selected_text').prop('placeholder', 'Tagsinput Default Text');
    $('#multiple_selected_value').prop('placeholder', 'Tagsinput Default Value');
    
    $('#multiple_with_search_container').hide();
}

function create_multiple_data() {
    
    $('#multiple_custom_data_container div.data input.value').off();
    $('#multiple_custom_data_container div.data input.value').change(function(e) {
        e.preventDefault();
        var text_equiv = $(this).parent().find('input.text');
        text_equiv.val( $(this).val().toLowerCase().replace(/ /g,'_') );
    });
    
    $('#multiple_custom_data_container div.data a.btn_add').off();
    $('#multiple_custom_data_container div.data a.btn_add').click(function(e) {
        e.preventDefault();
        
        var data_option = $(this).parent();
        var markup = '';

        markup += '<div class="data">\n';
        markup += '<input type="text" name="data[][text]" class="value input-xlarge" data-rule-required="true" data-rule-minlength="1" placeholder="Text" value="">\n';
        markup += '<input type="text" name="data[][value]" class="text input-xlarge" data-rule-required="true" data-rule-minlength="1" placeholder="Value" value="">\n';
        markup += '<input type="text" id="multiple_selected_image" name="data[][image]" class="image input-xlarge multiple-has-image" data-rule-required="true" data-rule-minlength="1" placeholder="URL or path" value="uploads/images/folder/some_image.jpg">\n';
        markup += '<a href="javascript:void(0)" class="btn btn-mini btn_add" rel="tooltip" title="Add Data Below"><i class="icon-plus"></i></a>\n';
        markup += '<a href="javascript:void(0)" class="btn btn-mini btn_delete" rel="tooltip" title="Delete This Data"><i class="icon-minus"></i></a>\n';
        markup += '</div>';
        
        data_option.after(markup);
        
        $('#multiple_custom_data_container div.data a.btn_delete').click(function(e) {
            var to_be_removed = $(this).parent();
            to_be_removed.remove();
        });
        
        create_multiple_data();
        
        if( ! $('#multiple_with_image').prop('checked') ) {
            $('.multiple-has-image').hide();
        }
        
    });
}

// ----------------------------------------------------------------------------- General Functions

function initialize_form_elements() {
    
    $('#custom_active_container').hide();
    $('#custom_inactive_container').hide();
    $('#custom_archived_container').hide();
    
//    $(".tagsinput").length > 0 && $(".tagsinput").tagsInput({width: "auto", height: "auto", defaultText: 'add another'});
    
    $('#upload_filetypes').tagsInput({width: "auto", height: "auto", defaultText: 'add another'});
    $('#multiple_default_values').tagsInput({width: "auto", height: "auto", defaultText: 'add another'});
    
    $(".form-validate").length > 0 && $(".form-validate").each(function() {
        var e = $(this).attr("id");
        $("#" + e).validate({errorElement: "span", errorClass: "help-block error", errorPlacement: function(e, t) {
            t.parents(".controls").append(e);
        }, highlight: function(e) {
            $(e).closest(".control-group").removeClass("error success").addClass("error");
        }, success: function(e) {
            e.addClass("valid").closest(".control-group").removeClass("error success").addClass("success");
        }});
    });
}

function remove_item(list_item) {
    $(list_item).parent().parent().remove();
}

$(function() {
    
    var icons = {
        'text'      : '<i class="icon-edit"></i>',
        'number'    : '#',
        'email'     : '<i class="icon-envelope"></i>',
        'url'       : '<i class="icon-globe"></i>',
        'password'  : '<i class="icon-lock"></i>',
        'confirm_password'  : '<i class="icon-unlock"></i>',
        'color'     :   '<i class="icon-tint"></i>',
        'location'  :   '<i class="icon-edit"></i>',
        'longitude' :   '<i class="icon-pushpin"></i>',
        'latitude'  :   '<i class="icon-pushpin"></i>'
    };
    
    initialize_form_elements();

//    -------------------------------------------------------------------------- Text
    $('#text_input_modal').on('shown', function() {
        $("#text_label").focus();
    });
    
    $('#text_confirm_password').slideUp();
    $('#text_icon').prop('checked', true);
    
    $('#generic_text_btn').click(function() {
        reset_text_form();
        to_text_input();
        $('#text_text').prop('checked', true);
        $('#text_input_modal').modal({
            width: '95%'
        });
    });
    
    // auto fill-up text name and id
    $('#text_label').change(function(e) {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#text_name').val(text_label);
        $('#text_id').val(text_label);
        $('#text_placeholder').val( $(this).val() );
    });
    
    // show hide change icon
    $('#text_icon').change(function() {
        if($(this).prop('checked') === true) {
            $('#text_change_icon_container').slideDown();
        } else {
            $('#text_change_icon_container').slideUp();
        }
    });
    
    $('#text_type').change(function() {
        var data_type = $(this).val();
        reset_text_form();
        if(data_type === 'text') {
            to_text_input();
        }
        if(data_type === 'number') {
            to_number_input();
        }
        if(data_type === 'email') {
            to_email_input();
        }
        if(data_type === 'url') {
            to_url_input();
        }
        if(data_type === 'password') {
            to_password_input();
        }
    });
    
    $('#text_btn').click(function(event) {
        event.preventDefault();
    });
    
    $('#text_save_btn').click(function(event) {
        event.preventDefault();
        $('#text_input_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#text_input_form').valid()) {
            var values = $('#text_input_form').serializeJSON();
            var list = $('<li>');

            // field data
            var type = values['type'];
            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var placeholder = values['placeholder'] !== undefined ? values['placeholder'] : '';
            var initial_value = values['initial_value'] !== undefined ? ' value="' + values['initial_value'] +'"' : '';
            var min_length = values['min_length'];
            var max_length = values['max_length'];
            
            // password
            var field_type = type === 'password' ? 'password' : 'text';
            var confirm_password = (values['confirm_password'] !== undefined && values['confirm_password'] !== '') ? true : false;
            
            // validations
            var validations = values['validations'];
            var required = $.inArray('required', validations) !== -1 ? ' data-rule-required="true" ' : ' ';
            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
            var valid_number = $.inArray('numeric', validations) !== -1 ? ' data-rule-number="true"="true" ' : ' ';
            var valid_email = $.inArray('valid_email', validations) !== -1 ? ' data-rule-email="true" ' : ' ';
            var valid_url = $.inArray('valid_url', validations) !== -1 ? ' data-rule-url="true" ' : ' ';

            // icons
            var icon = (values['icon'] !== undefined && values['icon'] !== '') ? true : false;
            var change_icon = (values['change_icon'] !== undefined && values['change_icon'] !== '') ? values['change_icon'] : icons[type];
            
            // spinner
            var spinner = (values['spinner'] !== undefined && values['spinner'] !== '') ? ' spinner' : '';
            var use_spinner = (values['spinner'] !== undefined && values['spinner'] !== '') ? true : false;
            var spinner_value = values['spinner'];
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';
            
            
            // html markup
            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label+ '</label>';
            }

            markup += '<div class="controls">';
            if(icon && ! use_spinner) {
                markup += '<div class="input-prepend"><span class="add-on">' +change_icon+ '</span>';
            }
            markup += '<input type="' +field_type+ '" name="' +field_name+ '" id="' +field_id+ '" class="input-xlarge' +spinner+ '"' +required+ 'data-rule-minlength="' +min_length+ '" data-rule-maxlenght="' +max_length+ '"' + valid_email + valid_url + valid_number + 'placeholder="' +placeholder+ '"' +initial_value+ '>';
            if(icon && ! use_spinner) {
                markup += '</div>';
            }
            markup += '</div></div>';
            
            if(field_type === 'password' && confirm_password) {

                markup += '<div class="control-group">';
                if(guideline) {
                    markup += '<label for="confirm_' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="Retype ' +field_name+ '">Confirm ' +label+ required_label+ '</label>';
                } else {
                    markup += '<label for="confirm_' +field_id+ '" class="control-label handle">Confirm ' +label+ required_label+ '</label>';
                }
                markup += '<div class="controls">';
                if(icon) {
                    markup += '<div class="input-prepend"><span class="add-on"><i class="icon-unlock"></i></span>';
                }
                markup += '<input type="' +field_type+ '" name="confirm_' +field_name+ '" id="confirm_' +field_id+ '" class="input-xlarge"' +required+ 'data-rule-minlength="' +min_length+ '" data-rule-maxlenght="' +max_length+ '" data-rule-equalto="' +field_id+ '" placeholder="Confirm ' +placeholder+ '" value="">';
                if(icon) {
                    markup += '</div>';
                }
                markup += '</div></div>';
            }
            
            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            // reinitialize popovers
            $('body').popover(popover_options);
            
            if(use_spinner) {
                $('ul#sortable li:last-child .spinner').spinner({step: spinner_value});
            }

            // hide modal
            $('#text_input_modal').modal('hide');
        }
        
        // submit form for validation purposes
        $('#text_input_form').submit();
    });
    
    // ------- Text Buttons ---------- //
    $('#text_btn').click(function() {
        reset_text_form();
        to_text_input();
        
        $('#text_label').val('');
        $('#text_name').val('');
        $('#text_id').val('');
        $('#text_placeholder').val('');
        
        $('#text_text').prop('checked', true);
        $('#text_type_container').hide();
        $('#text_input_modal').modal({
            width: '95%'
        });
    });
    
    $('#email_btn').click(function() {
        reset_text_form();
        to_email_input();
        
        $('#text_label').val('');
        $('#text_name').val('');
        $('#text_id').val('');
        $('#text_placeholder').val('');
        
        $('#text_email').prop('checked', true);
        $('#text_type_container').hide();
        $('#text_input_modal').modal({
            width: '95%'
        });
    });
    
    $('#url_btn').click(function() {
        reset_text_form();
        to_url_input();
        
        $('#text_label').val('');
        $('#text_name').val('');
        $('#text_id').val('');
        $('#text_placeholder').val('');
        
        $('#text_url').prop('checked', true);
        $('#text_type_container').hide();
        $('#text_input_modal').modal({
            width: '95%'
        });
    });
    
    $('#number_btn').click(function() {
        reset_text_form();
        to_number_input();
        
        $('#text_label').val('');
        $('#text_name').val('');
        $('#text_id').val('');
        $('#text_placeholder').val('');
        
        $('#text_number').prop('checked', true);
        $('#text_type_container').hide();
        $('#text_input_modal').modal({
            width: '95%'
        });
    });
    
    $('#password_btn').click(function() {
        reset_text_form();
        to_password_input();
        
        $('#text_label').val('');
        $('#text_name').val('');
        $('#text_id').val('');
        $('#text_placeholder').val('');
        
        $('#text_password').prop('checked', true);
        $('#text_type_container').hide();
        $('#text_input_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- Textarea
    $('#textarea_modal').on('shown', function() {
        $("#textarea_label").focus();
    });
    
    $('#generic_longtext_btn').click(function() {
        reset_textarea_form();
        $('#textarea_modal').modal({
            width: '95%'
        });
    });
    
    $('#textarea_type').change(function() {
        var data_type = $(this).val();
        if(data_type === 'textarea') {
            to_textarea_textarea();
        }
        if(data_type === 'wysiwyg') {
            to_textarea_wysiwyg();
        }
    });
    
    $('#textarea_type input').click(function() {
        var data_type = $('#textarea_type input:checked').val();
        if(data_type === 'textarea') {
            to_textarea_textarea();
        }
        if(data_type === 'wysiwyg') {
            to_textarea_wysiwyg();
        }
    });
    
    // auto fill-up long text name and id
    $('#textarea_label').change(function(e) {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#textarea_name').val(text_label);
        $('#textarea_id').val(text_label);
        $('#textarea_placeholder').val( $(this).val() );
    });
    
    $('#textarea_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#textarea_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#textarea_form').valid()) {

            var values = $( '#textarea_form' ).serializeJSON();

            var list = $('<li>');

            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var placeholder = values['placeholder'] !== undefined ? values['placeholder'] : '';
            var initial_value = values['initial_value'] !== undefined ? values['initial_value'] : '';
            var min_length = values['min_length'];
            var max_length = values['max_length'];
            var validations = values['validations'];

            var required = $.inArray('required', validations) === 1 ? ' data-rule-required="true" ' : ' ';  
            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
            
            var wysiwyg = (values['type'] === 'wysiwyg') ? true : false;
            var wysiwyg_class = (values['type'] === 'wysiwyg') ? 'ckeditor ' : '';
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';
            
            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label + '</label>';
            }

            markup += '<div class="controls">';
            markup += '<textarea name="' +field_name+ '" id="' +field_id+ '" class="' +wysiwyg_class+ 'span8" rows="5"' +required+ 'data-rule-minlength="' +min_length+ '" data-rule-maxlenght="' +max_length+ '" placeholder="' +placeholder+ '">' +initial_value+ '</textarea>';
            markup += '</div></div>';
            list.html(markup);

            $.data(list, 'controls', values);
            $('ul#sortable').append(list);

            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            // reinitialize popovers
            $('body').popover(popover_options);
            
            if(wysiwyg) {
//                $('ul#sortable li:last-child .cleditor').cleditor({width: 'auto'});
                CKEDITOR.replace(field_id, ckeditor_options);
            }

            // hide modal
            $('#textarea_modal').modal('hide');
        }
    });
    // ------------------- Long Text Buttons -------------- //
    $('#textarea_btn').click(function() {
        to_textarea_textarea();
        $('#textarea_type_container').hide();
        $('#textarea_modal').modal({
            width: '95%'
        });
    });
    
    $('#wysiwyg_btn').click(function() {
        to_textarea_wysiwyg();
        $('#textarea_type_container').hide();
        $('#textarea_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- Datetime
    $('#datetime_modal').on('shown', function() {
        $("#datetime_label").focus();
    });
    
    $('#generic_datetime_btn').click(function() {
        reset_datetime_form();
        $('#datetime_modal').modal({
            width: '95%'
        });
    });
    
    $('#datetime_type').change(function() {
        var data_type = $(this).val();
        if(data_type === 'time') {
            to_datetime_time();
        }
        if(data_type === 'date') {
            to_datetime_date();
        }
        if(data_type === 'daterange') {
            to_datetime_date_range();
        }
        if(data_type === 'datetime') {
            to_datetime_datetime();
        }
        if(data_type === 'datetimerange') {
            to_datetime_datetime_range();
        }
        if(data_type === 'timezone') {
            to_datetime_timezone();
        }
    });
    
    // auto fill-up long text name and id
    $('#datetime_label').change(function(e) {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#datetime_name').val(text_label);
        $('#datetime_id').val(text_label);
    });
    
    $('#datetime_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#datetime_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#datetime_form').valid()) {

            var values = $( '#datetime_form' ).serializeJSON();

            var list = $('<li>');
            
            var type = values['type'];
            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var validations = values['validations'];

            var required = $.inArray('required', validations) === 1 ? ' data-rule-required="true" ' : ' ';  
            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
            
            var placeholder = values['placeholder'] !== undefined ? ' placeholder="' + values['placeholder'] + '"' : '';
            var initial_value = values['initial_value'] !== undefined ? ' value="' + values['initial_value'] + '"' : '';

            var icon = (values['icon'] !== undefined && values['icon'] !== '') ? true : false;
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';

            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label + '</label>';
            }
            
            markup += '<div class="controls">';
            
            if(icon && (type === 'date' || type == 'daterange' || type === 'datetimerange')) {
                markup += '<div class="input-prepend"><span class="add-on"><i class="icon-calendar" data-time-icon="icon-time" data-date-icon="icon-calendar"></i></span>';
            }
            
            if(icon && (type === 'datetime')) {
                markup += '<div id="' +field_id+ '" class="input-prepend"><span class="add-on"><i class="icon-calendar"></i></span>';
            }
            
            if(type === 'date') {
                markup += '<input type="text" name="' +field_name+ '_date" id="' +field_id+ '_date" class="input-medium datepick" ' +required + placeholder + initial_value + '>\n</div>\n';
            }
            
            if(type === 'daterange') {
                markup += '<input type="text" name="' +field_name+ '_date" id="' +field_id+ '_date" class="input-large daterangepick" ' + required + placeholder + initial_value + '>\n</div>\n';
            }
            
            if(type === 'datetime') {
                markup += '<input type="text" name="' +field_name+ '_date" id="' +field_id+ '_date" class="input-large datetimepick" ' +required+ ' data-format="MM/dd/yyyy HH:mm:ss PP"' + placeholder + initial_value + '>\n</div>\n';
            }
            
            if(type === 'datetimerange') {
                markup += '<input type="text" name="' +field_name+ '_date" id="' +field_id+ '_date" class="input-large daterangepick" ' +required+ ' data-format="MM/dd/yyyy HH:mm:ss PP"' + placeholder + initial_value + '>\n</div>\n';
            }
            
            if(icon && (type === 'date' || type === 'daterange' || type === 'datetime' || type === 'datetimerange')) {
                markup += '</div>';
            }
            
            if(type === 'time') {
                markup += '<div class="bootstrap-timepicker"><input type="text" name="' +field_name+ '" id="' +field_id+ '" class="input-small timepick"' + initial_value + '></div>';
            }
            
            if(type === 'timezone') {
                markup += '<div class="pull-left span8"><select id="' +field_id+ '" name="' +field_name+ '" class="valid span12">';
                markup += '<option value="UM12">(UTC -12:00) Baker/Howland Island</option>';
                markup += '<option value="UM11">(UTC -11:00) Samoa Time Zone, Niue</option>';
                markup += '<option value="UM10">(UTC -10:00) Hawaii-Aleutian Standard Time, Cook Islands, Tahiti</option>';
                markup += '<option value="UM95">(UTC -9:30) Marquesas Islands</option>';
                markup += '<option value="UM9">(UTC -9:00) Alaska Standard Time, Gambier Islands</option>';
                markup += '<option value="UM8">(UTC -8:00) Pacific Standard Time, Clipperton Island</option>';
                markup += '<option value="UM7">(UTC -7:00) Mountain Standard Time</option>';
                markup += '<option value="UM6">(UTC -6:00) Central Standard Time</option>';
                markup += '<option value="UM5">(UTC -5:00) Eastern Standard Time, Western Caribbean Standard Time</option>';
                markup += '<option value="UM45">(UTC -4:30) Venezuelan Standard Time</option>';
                markup += '<option value="UM4">(UTC -4:00) Atlantic Standard Time, Eastern Caribbean Standard Time</option>';
                markup += '<option value="UM35">(UTC -3:30) Newfoundland Standard Time</option>';
                markup += '<option value="UM3">(UTC -3:00) Argentina, Brazil, French Guiana, Uruguay</option>';
                markup += '<option value="UM2">(UTC -2:00) South Georgia/South Sandwich Islands</option>';
                markup += '<option value="UM1">(UTC -1:00) Azores, Cape Verde Islands</option>';
                markup += '<option value="UTC">(UTC) Greenwich Mean Time, Western European Time</option>';
                markup += '<option value="UP1">(UTC +1:00) Central European Time, West Africa Time</option>';
                markup += '<option value="UP2" selected="selected">(UTC +2:00) Central Africa Time, Eastern European Time, Kaliningrad Time</option>';
                markup += '<option value="UP3">(UTC +3:00) Moscow Time, East Africa Time</option>';
                markup += '<option value="UP35">(UTC +3:30) Iran Standard Time</option>';
                markup += '<option value="UP4">(UTC +4:00) Azerbaijan Standard Time, Samara Time</option>';
                markup += '<option value="UP45">(UTC +4:30) Afghanistan</option>';
                markup += '<option value="UP5">(UTC +5:00) Pakistan Standard Time, Yekaterinburg Time</option>';
                markup += '<option value="UP55">(UTC +5:30) Indian Standard Time, Sri Lanka Time</option>';
                markup += '<option value="UP575">(UTC +5:45) Nepal Time</option>';
                markup += '<option value="UP6">(UTC +6:00) Bangladesh Standard Time, Bhutan Time, Omsk Time</option>';
                markup += '<option value="UP65">(UTC +6:30) Cocos Islands, Myanmar</option>';
                markup += '<option value="UP7">(UTC +7:00) Krasnoyarsk Time, Cambodia, Laos, Thailand, Vietnam</option>';
                markup += '<option value="UP8">(UTC +8:00) Australian Western Standard Time, Beijing Time, Irkutsk Time</option>';
                markup += '<option value="UP875">(UTC +8:45) Australian Central Western Standard Time</option>';
                markup += '<option value="UP9">(UTC +9:00) Japan Standard Time, Korea Standard Time, Yakutsk Time</option>';
                markup += '<option value="UP95">(UTC +9:30) Australian Central Standard Time</option>';
                markup += '<option value="UP10">(UTC +10:00) Australian Eastern Standard Time, Vladivostok Time</option>';
                markup += '<option value="UP105">(UTC +10:30) Lord Howe Island</option>';
                markup += '<option value="UP11">(UTC +11:00) Magadan Time, Solomon Islands, Vanuatu</option>';
                markup += '<option value="UP115">(UTC +11:30) Norfolk Island</option>';
                markup += '<option value="UP12">(UTC +12:00) Fiji, Gilbert Islands, Kamchatka Time, New Zealand Standard Time</option>';
                markup += '<option value="UP1275">(UTC +12:45) Chatham Islands Standard Time</option>';
                markup += '<option value="UP13">(UTC +13:00) Phoenix Islands Time, Tonga</option>';
                markup += '<option value="UP14">(UTC +14:00) Line Islands</option>';                                         
                markup += '</select></div>';
            }
            
            markup += '</div></div></div>';

            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            // reinitialize popovers
            $('body').popover(popover_options);

            if(type === 'time') {
                $('ul#sortable li:last-child .timepick').timepicker({
                    defaultTime: "current",
                    minuteStep: 1,
                    disableFocus: !0,
                    showMeridian: false,
                    template: "dropdown"
                });
            }
            if(type === 'date') {
                $('ul#sortable li:last-child .datepick').datepicker({autoclose:true});
            }
            if(type === 'daterange') {
                $('ul#sortable li:last-child .daterangepick').daterangepicker({});
            }
            if(type === 'datetime') {
                $('ul#sortable li:last-child .datetimepick').datetimepicker({language: 'en', pick12HourFormat: true});
            }
            if(type === 'datetimerange') {
                $('ul#sortable li:last-child .daterangepick').daterangepicker({timePicker: true, timePickerIncrement: 1, format: 'MM/DD/YYYY h:mm A'});
            }
            
            // hide modal
            $('#datetime_modal').modal('hide');
        }
    });
    
    // ------------------- Datetime Buttons -------------- //
    $('#time_btn').click(function() {
        reset_datetime_form();
        to_datetime_time();
        $('#datetime_type_container').hide();
        $('#datetime_modal').modal({
            width: '95%'
        });
    });
    
    $('#timezone_btn').click(function() {
        reset_datetime_form();
        to_datetime_timezone();
        $('#datetime_type_container').hide();
        $('#datetime_modal').modal({
            width: '95%'
        });
    });
    
    $('#date_btn').click(function() {
        reset_datetime_form();
        to_datetime_date();
        $('#datetime_type_container').hide();
        $('#datetime_modal').modal({
            width: '95%'
        });
    });
    
    $('#daterange_btn').click(function() {
        reset_datetime_form();
        to_datetime_date_range();
        $('#datetime_type_container').hide();
        $('#datetime_modal').modal({
            width: '95%'
        });
    });
    
    $('#datetime_btn').click(function() {
        reset_datetime_form();
        to_datetime_datetime();
        $('#datetime_type_container').hide();
        $('#datetime_modal').modal({
            width: '95%'
        });
    });
    
    $('#datetimerange_btn').click(function() {
        reset_datetime_form();
        to_datetime_datetime_range();
        $('#datetime_type_container').hide();
        $('#datetime_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- File Upload
    // show upload modal
    $('#upload_modal').on('shown', function() {
        $("#upload_label").focus();
    });
    
    // reset upload form, add click event to generic uploader button
    $('#generic_file_uploader_btn').click(function() {
        reset_upload_form();
        $('#upload_modal').modal({
            width: '95%'
        });
    });
    
    // toggle show/hide resize inputs
    $('#upload_resize').change(function() {
        if($(this).prop('checked') === true) {
            $('#upload_width_container').slideDown();
            $('#upload_height_container').slideDown();
            
            $('#upload_width').prop('data-rule-required', true);
            $('#upload_height').prop('data-rule-required', true);
            
        } else {
            $('#upload_width_container').slideUp();
            $('#upload_height_container').slideUp();
            
            $('#upload_width').prop('data-rule-required', false);
            $('#upload_height').prop('data-rule-required', false);
        }
    });
    
    $('#upload_type').change(function() {
        var data_type = $(this).val();
        if(data_type === 'upload_image') {
            to_upload_image();
        }
        if(data_type === 'upload_url') {
            to_upload_url();
        }
        if(data_type === 'upload_file') {
            to_upload_file();
        }
        if(data_type === 'upload_multiple') {
            to_upload_multiple();
        }
    });
    
    // auto fill-up long text name and id
    $('#upload_label').change(function(e) {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#upload_name').val(text_label);
        $('#upload_id').val(text_label);
        $('#upload_placeholder').val( $(this).val() );
    });
    
    $('#upload_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#upload_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#upload_form').valid()) {

            var values = $( '#upload_form' ).serializeJSON();

            var list = $('<li>');
            
            var type = values['type'];
            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var validations = values['validations'];

            var required = $.inArray('required', validations) === 1 ? ' data-rule-required="true" ' : ' ';
            var required_label = $.inArray('required', validations) === 1 ? ' *' : '';
            var icon = (values['icon'] !== undefined && values['icon'] !== '') ? true : false;
            var resize = (values['resize'] !== undefined && values['resize'] !== '') ? true : false;
            var width = (values['width'] !== undefined && values['width'] !== '') ? values['width'] : '';
            var height = (values['height'] !== undefined && values['height'] !== '') ? values['height'] : '';
            var extensions = (values['filetypes'] !== undefined && values['filetypes'] !== '') ? values['filetypes'] : '';
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';
            
            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label + '</label>';
            }
            
            markup += '<div class="controls">';
            
            if(type === 'upload_file') {
                markup += '<div class="fileupload fileupload-new" data-provides="fileupload">';
                markup += '<div class="input-append">';
                markup += '<div class="uneditable-input span3"><i class="icon-file fileupload-exists"></i> <span class="fileupload-preview"></span></div><span class="btn btn-file"><span class="fileupload-new">Select file</span><span class="fileupload-exists">Change</span><input type="file" name="' +field_name+ '" id="' +field_id+ '" /></span><a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>';
                markup += '</div></div>';
            }
            
            if(type === 'upload_image') {
                markup += '<div class="fileupload fileupload-new" data-provides="fileupload">';
                markup += '<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="' +base_url+ 'img/cms/no_image.gif" /></div>';
                markup += '<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>';
                markup += '<div>';
                markup += '<span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input id="' +field_id+ '" name="' +field_name+ '" type="file" /></span>';
                markup += '<a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>';
                markup += '</div></div>';
            }

            if(type === 'upload_multiple') {
                markup += '<div class="plupload"></div>';
                if(guideline) {
                    markup += '<span class="help-block">' +guideline_text+ '</span>';
                }
            }

            markup += '</div></div>';
            
            if(type === 'upload_url') {
                markup = '';
                markup += '<div id="' +field_id+ '_radio_container" class="control-group">';
                markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
                
                if(guideline) {
                    markup += '<label class="control-label handle"  rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="You may choose to upload an image via URL or via file upload.">URL or Upload</label><div class="controls">';
                } else {
                    markup += '<label class="control-label handle">URL or Upload</label><div class="controls">';
                }

                markup += '<label class="radio"><input type="radio" name="' + field_id + '_image_container" id="' + field_id + '_url_check" value="url" checked> Specify Image URL</label>';
                markup += '<label class="radio"><input type="radio" name="' + field_id + '_image_container" id="' + field_id + '_file_check" value="upload"> Upload an Image File</label>';                           
                
                markup += '</div></div>';
                              
                markup += '<div id="' +field_id+ '_url_container" class="control-group">';
                markup += '<label for="' +field_id+ '_url" class="control-label handle">' +label + required_label + '</label>';
                markup += '<div class="controls">';
                
                if(icon) {
                     markup += '<div class="input-prepend"><span class="add-on"><i class="icon-globe"></i></span>';
                }
                markup += '<input type="text" name="' +field_name+ '_url" id="' +field_id+ '_url" class="input-xlarge" data-rule-minlength="2" data-rule-maxlength="1000"' +required+ 'data-rule-url="true" placeholder="http://domain_name/image.jpg" value="">';
                if(icon) {
                    markup += '</div>';
                }
                
                markup += '</div></div>';
                
                markup += '<div id="' +field_id+ '_file_container" class="control-group">';
                markup += '<label for="' +field_id+ '_file" class="control-label handle">' +label + required_label + '</label>';
                markup += '<div class="controls">';
                markup += '<div class="fileupload fileupload-new" data-provides="fileupload">';
                markup += '<div class="fileupload-new thumbnail" style="width: 200px; height: 150px;"><img src="' +base_url+ 'img/cms/no_image.gif" /></div>';
                markup += '<div class="fileupload-preview fileupload-exists thumbnail" style="max-width: 200px; max-height: 150px; line-height: 20px;"></div>';
                markup += '<div>';
                markup += '<span class="btn btn-file"><span class="fileupload-new">Select image</span><span class="fileupload-exists">Change</span><input name="' +field_name+ '_file" id="' +field_id+ '_file" type="file" /></span>';
                markup += '<a href="#" class="btn fileupload-exists" data-dismiss="fileupload">Remove</a>';
                markup += '</div></div></div></div>';
            }

            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            // reinitialize popovers
            $('body').popover(popover_options);
            
            if(type === 'upload_url') {
                url_to_upload(field_id);
            }
            
            if(type === 'upload_multiple') {
                
                var new_extensions = 'jpg,png,gif';
                var new_size = {};
                if(resize && width !== '' && height !== '') {
                    new_size['width'] = width;
                    new_size['height'] = height;
                    new_size['quality'] = 90;
                }
                
                if(extensions !== '') {
                    new_extensions = extensions;
                }

                var $el = $("ul#sortable li:last-child .plupload");
                $el.pluploadQueue({
                    runtimes : 'html5,flash,html4,silverlight,browserplus,gears',
                    url :  base_url + 'fileuploader/upload',
                    max_file_size : '10mb',
                    chunk_size : '1mb',
                    unique_names : true,
                    resize : new_size,
                    filters: [{
                        title: "Image files", 
                        extensions: new_extensions
                    }],
                    flash_swf_url : base_url + 'js/plugins/plupload/plupload.flash.swf',
                    silverlight_xap_url : base_url +  'js/plugins/plupload/plupload.silverlight.xap'
                });
                $(".plupload_header").remove();
                $(".plupload_progress_container").addClass("progress").addClass('progress-striped');
                $(".plupload_progress_bar").addClass("bar");
                $(".plupload_button").each(function(){
                    if($(this).hasClass("plupload_add")){
                        $(this).attr("class", 'btn pl_add btn-primary').html("<i class='icon-plus-sign'></i> "+$(this).html());
                    } else {
                        $(this).attr("class", 'btn pl_start btn-success').html("<i class='icon-cloud-upload'></i> "+$(this).html());
                    }
                });
            }
            
            // hide modal
            $('#upload_modal').modal('hide');
        }
    });
    
    // ------------------- File Upload Buttons -------------- //
    $('#file_upload_btn').click(function() {
        to_upload_file();
        $('#upload_type_container').hide();
        $('#upload_modal').modal({
            width: '95%'
        });
    });
    
    $('#image_upload_btn').click(function() {
        to_upload_image();
        $('#upload_type_container').hide();
        $('#upload_modal').modal({
            width: '95%'
        });
    });

    $('#url_upload_btn').click(function() {
        to_upload_url();
        $('#upload_type_container').hide();
        $('#upload_modal').modal({
            width: '95%'
        });
    });
    
    $('#multiple_upload_btn').click(function() {
        to_upload_multiple();
        $('#upload_type_container').hide();
        $('#upload_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- Color Picker

    $('#color_modal').on('shown', function() {
        $("#color_label").focus();
    });
    
    $('#generic_color_btn').click(function() {
        $('#color_modal').modal({
            width: '95%'
        });
    });
    
    $('#color_icon').prop('checked', true);
    
    // show hide change icon
    $('#color_icon').change(function() {
        if($(this).prop('checked') === true) {
            $('#change_color_icon_container').slideDown();
        } else {
            $('#change_color_icon_container').slideUp();
        }
    });
    
    $('#color_format').change(function() {
        if( $(this).val() === 'hex') {
            $('#color_placeholder').val('#ffffff');
            $('#color_initial_value').val('#ffffff');
        }
        if( $(this).val() === 'rgb') {
            $('#color_placeholder').val('rgb(255,255,255)');
            $('#color_initial_value').val('rgb(255,255,255)');
        }
        if( $(this).val() === 'rgba') {
            $('#color_placeholder').val('rgb(255,255,255,0.50)');
            $('#color_initial_value').val('rgba(255,255,255,0.50)');
        }
        if( $(this).val() === 'hsl') {
            $('#color_placeholder').val('hsl(255,50%,50%)');
            $('#color_initial_value').val('hsl(255,50%,50%)');
        }
        if( $(this).val() === 'hsla') {
            $('#color_placeholder').val('hsla(255,50%,50%,0.50)');
            $('#color_initial_value').val('hsla(255,50%,50%,0.50)');
        }
    });
    
    // auto fill-up color name and id
    $('#color_label').change(function() {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#color_name').val(text_label);
        $('#color_id').val(text_label);
    });
    
    $('#color_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#color_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });

        if( $('#color_form').valid()) {

            var values = $( '#color_form' ).serializeJSON();

            var list = $('<li>');
            
            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var placeholder = values['placeholder']  !== undefined ? values['placeholder'] : '';
            var initial_value = values['initial_value'] !== undefined ? ' value="' + values['initial_value'] +'"' : '';
            var validations = values['validations'];
            var format = ( values['format'] !== undefined && values['format'] !== '') ? values['format'] : 'hex';
            
            var size = ' input-large';
            if(format === 'hex') {
                size = ' input-mini';
            }
            if(format === 'rgb' || format === 'hsl') {
                size = ' input-medium';
            }
            
            // icons
            var icon = (values['icon'] !== undefined && values['icon'] !== '') ? true : false;
            var change_icon = (values['change_icon'] !== undefined && values['change_icon'] !== '') ? values['change_icon'] : icons['color'];
            
            var required = $.inArray('required', validations) === 1 ? ' data-rule-required="true" ' : ' ';  
            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';
            
            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label + '</label>';
            }

            markup += '<div class="controls">';
            if(icon) {
                markup += '<div class="input-prepend"><span class="add-on">' +change_icon+ '</i></span>';
            }
            markup += '<input type="text" name="' +field_name+ '" id="' +field_id+ '" class="colorpick '+ size +'"' +required+ 'placeholder="' +placeholder+ '"' +initial_value+ '>';
            if(icon) {
                 markup += '</div>';
            }
            markup += '</div></div>';

            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            // reinitialize popovers
            $('body').popover(popover_options);
            
            $("ul#sortable li:last-child .colorpick").colorpicker({
                format: format
            });
            
            // hide modal
            $('#color_modal').modal('hide');
        }
    });
    // ------------------- Color Button -------------- //
    $('#color_btn').click(function() {
        reset_color_form();
        $('#color_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- Geolocation
    $('#geolocation_modal').on('shown', function() {
        $("#geolocation_label").focus();
    });
    
    $('#generic_geolocation_btn').click(function() {
        reset_geolocation_form();
        $('#geolocation_modal').modal({
            width: '95%'
        });
    });
    
    $('#geolocation_icon').prop('checked', true);
    
    // show hide change icon
    $('#geolocation_icon').change(function() {
        if($(this).prop('checked') === true) {
            $('#gelocation_location_icon_container').slideDown();
            $('#gelocation_longitude_icon_container').slideDown();
            $('#gelocation_latitude_icon_container').slideDown();
        } else {
            $('#gelocation_location_icon_container').slideUp();
            $('#gelocation_longitude_icon_container').slideUp();
            $('#gelocation_latitude_icon_container').slideUp();
        }
    });
    
    // auto fill-up long text name and id
    $('#geolocation_label').change(function() {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#geolocation_name').val(text_label);
        $('#geolocation_id').val(text_label);
        $('#geolocation_placeholder').val( $(this).val() );
    });
    
    $('#geolocation_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#geolocation_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });

        if( $('#geolocation_form').valid()) {

            var values = $( '#geolocation_form' ).serializeJSON();

            var list = $('<li>');
            
            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var placeholder = values['placeholder'] !== undefined ? ' placeholder="' +values['placeholder']+ '"' : '';
            var initial_value = values['initial_value'] !== undefined ? ' value="' + values['initial_value'] +'"' : '';
            var initial_longitude = values['initial_longitude'];
            var initial_latitude = values['initial_latitude'];
            var validations = values['validations'];
            
            // icons
            var icon = (values['icon'] !== undefined && values['icon'] !== '') ? true : false;
            var location_icon = (values['location_icon'] !== undefined && values['location_icon'] !== '') ? values['location_icon'] : icons['location'];
            var longitude_icon = (values['longitude_icon'] !== undefined && values['longitude_icon'] !== '') ? values['longitude_icon'] : icons['longitude'];
            var latitude_icon = (values['latitude_icon'] !== undefined && values['latitude_icon'] !== '') ? values['latitude_icon'] : icons['latitude'];
            
            var required = $.inArray('required', validations) === 1 ? ' data-rule-required="true" ' : ' ';  
            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';

            var markup = '';
            
            // map canvas
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            if(guideline) {
                markup += '<label for="' +field_id+ '_map" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">Plot ' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '_map" class="control-label handle">Plot ' +label + required_label + '</label>';
            }
            markup += '<div class="controls">';
            markup += '<div id="' +field_id+ '_map" style="width:100%; height:300px;"></div>';
            markup += '</div></div>';
            
            // location input
            markup += '<div class="control-group">';
            markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label + '</label>';
            markup += '<div class="controls">';
            if(icon) {
                markup += '<div class="input-prepend"><span class="add-on">' +location_icon+ '</i></span>';
            }
            markup += '<input type="text" name="' +field_name+ '" id="' +field_id+ '" class="input-xlarge"' +required+ 'data-rule-minlength="1" data-rule-maxlength="1000"' + placeholder + initial_value + '>';
            if(icon) {
                 markup += '</div>';
            }
            markup += '</div></div>';
            
            // longitude
            markup += '<div class="control-group">';
            markup += '<label for="' +field_id+ '_longitude" class="control-label handle">' +label +' Longitude'+ required_label + '</label>';
            markup += '<div class="controls">';
            
            if(icon) {
                markup += '<div class="input-prepend"><span class="add-on">' +longitude_icon+ '</i></span>';
            }
            markup += '<input type="text" name="' +field_name+ '_longitude" id="' +field_id+ '_longitude" class="input-xlarge"' +required+ 'data-rule-minlength="1" data-rule-maxlength="1000" data-rule-number="true" placeholder="120.61758366806225" value="120.61758366806225">';
            if(icon) {
                 markup += '</div>';
            }
            markup += '</div></div>';

            // latitude
            markup += '<div class="control-group">';
            markup += '<label for="' +field_id+ '_latitude" class="control-label handle">' +label +' Latitude'+ required_label + '</label>';
            markup += '<div class="controls">';
            
            if(icon) {
                markup += '<div class="input-prepend"><span class="add-on">' +latitude_icon+ '</i></span>';
            }
            markup += '<input type="text" name="' +field_name+ '_latitude" id="' +field_id+ '_latitude" class="input-xlarge"' +required+ 'data-rule-minlength="1" data-rule-maxlength="1000" data-rule-number="true" placeholder="16.413640135538014" value="16.413640135538014">';
            if(icon) {
                 markup += '</div>';
            }
            markup += '</div></div>';

            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            // reinitialize popovers
            $('body').popover(popover_options);
            
            initialize_map(field_id, initial_longitude, initial_latitude);
            
//            initialize_map(field_id + '_map', field_id + '_longitude', field_id + '_latitude', '120.61758366806225', '16.413640135538014');
            
            // hide modal
            $('#geolocation_modal').modal('hide');
        }
    });
    // ------------------- Geolocation Button -------------- //
    $('#geolocation_btn').click(function() {
        reset_geolocation_form();
        $('#geolocation_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- Toggle
    $('#switch_on_container').slideUp();
    $('#switch_off_container').slideUp();

    // show hide change icon
    $('#switch').change(function() {
        if($(this).prop('checked') === true) {
            $('#switch_on_container').slideDown();
            $('#switch_off_container').slideDown();
        } else {
            $('#switch_on_container').slideUp();
            $('#switch_off_container').slideUp();
        }
    });
    
    $('#toggle_modal').on('shown', function() {
        $("#toggle_label").focus();
    });

    // auto fill-up toggle name and id
    $('#toggle_label').change(function() {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#toggle_name').val(text_label);
        $('#toggle_id').val(text_label);
    });
    
    $('#toggle_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#toggle_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });

        if( $('#toggle_form').valid()) {

            var values = $( '#toggle_form' ).serializeJSON();

            var list = $('<li>');
            
            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var validations = values['validations'];
            var placeholder = values['placeholder'] !== undefined ? ' placeholder="' +values['placeholder']+ '"' : '';
            
            var required = $.inArray('required', validations) === 1 ? ' data-rule-required="true" ' : ' ';  
            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
            
            var on_text = values['switch_on'] !== undefined ? ' data-on-text="' +values['switch_on']+'" ' : 'ON';
            var off_text = values['switch_off'] !== undefined ? ' data-off-text="' +values['switch_off']+' "' : 'OFF';
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';
            
            var use_switch = $('#switch').prop('disabled');
            if( ! use_switch) {
                use_switch = (values['switch'] === 'yes') ? true : false;
            }
            
            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label + '</label>';
            }

            markup += '<div class="controls">';
                        
            markup += '<input type="checkbox" name="' +field_name+ '" id="' +field_id+ '" class="switch has-switch"' + required + on_text + off_text + placeholder + '>';
            markup += '</div></div>';

            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            // reinitialize popovers
            $('body').popover(popover_options);
            
            if(use_switch) {
                $("ul#sortable li:last-child .switch").bootstrapSwitch();
            }
//            $("ul#sortable li:last-child .colorpick").colorpicker();
            
            // hide modal
            $('#toggle_modal').modal('hide');
        }
    });
    // ------------------- Toggle Button -------------- //
    $('#generic_toggle_btn').click(function() {
        reset_toggle_form();
        $('#toggle_modal').modal({
            width: '95%'
        });
    });
    
    $('#toggle_btn').click(function() {
        reset_toggle_form();
        to_switch();
        $('#toggle_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- Single Input
    $('#single_modal').on('shown', function() {
        $("#single_label").focus();
    });
    
    $('#generic_single_btn').click(function() {
        reset_single_form();
        $('#single_modal').modal({
            width: '95%'
        });
    });
    
    // clear all data fields
    $('#single_clear_btn').click(function() {
        $('#single_custom_data_container div.data').not('#single_custom_data_container div.data:first-child').remove();
    });
    
    create_single_data();
    
    // auto fill-up single name and id
    $('#single_label').change(function() {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#single_name').val(text_label);
        $('#single_id').val(text_label);
    });
    
    $('#single_db_singular').change(function() {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#single_db_plural').val( $(this).val() + 's');
        $('#single_db_foreign_key').val( text_label + '_id');
    });
    
    $('#single_type').change(function() {
        var value = $(this).val();
        if(value === 'dropdown') {
            $('#single_modal_title').text('Dropdown Menu');
            $('#single_save_btn').text('Create Dropdown Menu');
            $('#single_selected_text').prop('placeholder', 'Option Default Text');
            $('#single_selected_value').prop('placeholder', 'Option Default Value');
            $('#single_with_search_container').slideDown();
        }
        
        if(value === 'radio') {
            $('#single_modal_title').text('Radio Buttons');
            $('#single_save_btn').text('Create Radio Buttons');
            $('#single_selected_text').prop('placeholder', 'Radio Default Text');
            $('#single_selected_value').prop('placeholder', 'Radio Default Value');
            $('#single_with_search_container').slideUp();
        }
    });
    
    $('#single_data').change(function() {
        var value = $(this).val();
        if(value === 'custom') {
            $('#single_custom_data_container').slideDown();
            
            $('#single_db_table_name_container').slideUp();
            $('#single_db_table_value_container').slideUp();
            $('#single_db_table_text_container').slideUp();
            $('#single_db_table_image_container').slideUp();
            
            $('#single_db_foreign_key_container').slideUp();
            $('#single_db_plural_container').slideUp();
            $('#single_db_singular_container').slideUp();
        }
        
        if(value === 'database') {
            $('#single_db_table_name_container').slideDown();
            $('#single_db_table_value_container').slideDown();
            $('#single_db_table_text_container').slideDown();
            if( $('#single_with_image').prop('checked') ) {
                $('#single_db_table_image_container').slideDown();
            }
            
            $('#single_db_foreign_key_container').slideDown();
            $('#single_db_plural_container').slideDown();
            $('#single_db_singular_container').slideDown();
            
            $('#single_custom_data_container').slideUp();
        }
    });
    
    $('#single_with_image').change(function() {
        if($(this).prop('checked') === true) {
            $('.has-image').slideDown();
            if( $('#single_data').val() === 'custom') {
                $('#single_db_table_image_container').hide();
            }
        } else {
            $('.has-image').slideUp();
        }
    });
    
    $('#single_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#single_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });

        if( $('#single_form').valid()) {

            var values = $( '#single_form' ).serializeJSON();

            var list = $('<li>');
            
            var type = values['type'];
            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var validations = values['validations'];
            
            var required = $.inArray('required', validations) === 1 ? ' data-rule-required="true" ' : ' ';  
            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
            
            var search = (values['with_search'] !== undefined && values['with_search'] !== '') ? true : false;
            var search_class = (values['with_search'] !== undefined && values['with_search'] !== '') ? ' chosen-select ' : '';
            
            var data_source = values['single_data'];
            var data = values['data'];
            
            var database_name = values['db_table_name'];
            var database_attribute_value = values['db_table_value'];
            var database_attribute_text = values['db_table_text'];
            var database_attribute_image = (values['db_table_image'] !== undefined && values['db_table_image'] !== '') ? values['db_table_image'] : 'none';
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';
            
            var with_image = $('#single_with_image').prop('checked') ? true : false;
            
            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label + '</label>';
            }
            markup += '<div class="controls">';
            
            if(type === 'dropdown') {
                
                markup += '<div class="input-xlarge">';
                markup += '<select name="' +field_name+ '" id="' +field_id+ '" class="' +search_class+ '">';
                
                if(data_source === 'custom') {
                    $.each(data, function(idx, obj) {
                        
                        var value = (data[idx]['value'] !== undefined) ? ' value="' +data[idx]['value']+ '"' : '';
                        var text = (data[idx]['text'] !== undefined) ? data[idx]['text'] : '';
                        var data_image = (data[idx]['image'] !== undefined) ? data[idx]['image'] : '';
                        
                        if( with_image ) {
                            if( data_image.indexOf('http') != -1 || data_image.indexOf('www') != -1 ) {
                                data_image = ' data-img-src="' + data_image + '"';
                            } else {
                                data_image = ' data-img-src="' + base_url + data_image + '"';
                            }
                        } else {
                            data_image = '';
                        }

                        markup += '<option' + value + data_image + '>' +text+ '</option>';
                        
                    });
                }
                
                if(data_source === 'database') {
                    var single_data = {};
                    single_data['db_name'] = database_name;
                    single_data['db_attr_value'] = database_attribute_value;
                    single_data['db_attr_text'] = database_attribute_text;
                    single_data['db_attr_image'] = database_attribute_image;
                    
                    var db_data = get_db_data(base_url + 'generator/retrieve_data', single_data);
                    $.each(db_data, function(idx, obj) {
                        
                        var value = (db_data[idx]['value'] !== undefined) ? ' value="' +db_data[idx]['value']+ '"' : '';
                        var text = (db_data[idx]['text'] !== undefined) ? db_data[idx]['text'] : '';
                        var data_image = (db_data[idx]['image'] !== undefined) ? db_data[idx]['image'] : '';
                        
                        if( with_image ) {
                            data_image = ' data-img-src="' + base_url + $('#single_image_path').val() + data_image + '"';
                        } else {
                            data_image = '';
                        }
                        
                        markup += '<option' + value + data_image + '>' +text+ '</option>';

                    });
                }
                markup += '</select></div>';
            }
            
            if(type === 'radio') {
                
                if(data_source === 'custom') {
                    $.each(data, function(idx, obj) {
                        if(idx === 0) {
                            markup += '<label class="radio"><input type="radio" name="' +field_name+ '" value="' +data[idx]['value']+ '" checked>' +data[idx]['text']+ '</label>';
                        } else {
                            markup += '<label class="radio"><input type="radio" name="' +field_name+ '" value="' +data[idx]['value']+ '">' +data[idx]['text']+ '</label>';
                        }
                    });
                }
                
                if(data_source === 'database') {
                    single_data = {};
                    single_data['db_name'] = database_name;
                    single_data['db_attr_value'] = database_attribute_value;
                    single_data['db_attr_text'] = database_attribute_text;
                    
                    db_data = get_db_data(base_url + 'generator/retrieve_data', single_data);
                    $.each(db_data, function(idx, obj) {
                        if(idx === 0) {
                            markup += '<label class="radio"><input type="radio" name="' +field_name+ '" value="' +db_data[idx]['value']+ '" checked>' +db_data[idx]['text']+ '</label>';
                        } else {
                            markup += '<label class="radio"><input type="radio" name="' +field_name+ '" value="' +db_data[idx]['value']+ '">' +db_data[idx]['text']+ '</label>';
                        }
                    });
                }
            }
            
            markup += '</div></div>';

            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            // reinitialize popovers
            $('body').popover(popover_options);
            
            if( search || with_image) {
                $("ul#sortable li:last-child .chosen-select").chosen({});
            }
            
            // hide modal
            $('#single_modal').modal('hide');
        }
    });
    // ------------------- Single Button -------------- //
    $('#radio_btn').click(function() {
        reset_single_form();
        to_single_radio();
        $('#single_type_container').hide();
        $('#single_modal').modal({
            width: '95%'
        });
    });
    
    $('#single_dropdown_btn').click(function() {
        reset_single_form();
        to_single_dropdown();
        $('#single_type_container').hide();
        $('#single_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- Multiple Input
    $('#multiple_modal').on('shown', function() {
        $("#multiple_label").focus();
    });
    
    $('#generic_multiple_btn').click(function() {
        reset_multiple_form();
        $('#multiple_modal').modal({
            width: '95%'
        });
    });
    
    // clear all data fields
    $('#multiple_clear_btn').click(function() {
        $('#multiple_custom_data_container div.data').not('#multiple_custom_data_container div.data:first-child').remove();
    });
    
    create_multiple_data();
    
    // auto fill-up multiple name and id
    $('#multiple_label').change(function() {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#multiple_name').val(text_label);
        $('#multiple_id').val(text_label);
    });
    
    $('#multiple_db_singular').change(function() {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#multiple_db_plural').val( $(this).val() + 's');
        $('#multiple_db_foreign_key').val( text_label + '_id');
    });
    
    $('#multiple_type').change(function() {
        var value = $(this).val();
        if(value === 'multiple_dropdown') {
            $('#multiple_modal_title').text('Dropdown Menu');
            $('#multiple_save_btn').text('Create Dropdown Menu');
            
            $('#multiple_default_values_container').slideUp();
            $('#multiple_data_container').slideDown();
            $('#multiple_custom_data_container').slideDown();
            
            $('#multiple_selected_text').prop('placeholder', 'Option Default Text');
            $('#multiple_selected_value').prop('placeholder', 'Option Default Value');
        }
        
        if(value === 'checkbox') {
            $('#multiple_modal_title').text('Checkbox');
            $('#multiple_save_btn').text('Create Checkbox');
            
            $('#multiple_default_values_container').slideUp();
            $('#multiple_data_container').slideDown();
            $('#multiple_custom_data_container').slideDown();
            
            $('#multiple_selected_text').prop('placeholder', 'Checkbox Default Text');
            $('#multiple_selected_value').prop('placeholder', 'Checkbox Default Value');
        }
        
        if(value === 'tagsinput') {
            $('#multiple_modal_title').text('Tagsinput');
            $('#multiple_save_btn').text('Create Tagsinput');
            
            $('#multiple_default_values_container').slideDown();
            $('#multiple_data_container').slideUp();
            $('#multiple_custom_data_container').slideUp();
            
            $('#multiple_selected_text').prop('placeholder', 'Tagsinput Default Text');
            $('#multiple_selected_value').prop('placeholder', 'Tagsinput Default Value');
        }
    });
    
    $('#multiple_data').change(function() {
        var value = $(this).val();
        if(value === 'custom') {
            $('#multiple_custom_data_container').slideDown();
            
            $('#multiple_db_table_name_container').slideUp();
            $('#multiple_db_table_value_container').slideUp();
            $('#multiple_db_table_text_container').slideUp();
            $('#multiple_db_table_image_container').slideUp();
            
            $('#multiple_db_foreign_key_container').slideUp();
            $('#multiple_db_plural_container').slideUp();
            $('#multiple_db_singular_container').slideUp();
        }
        
        if(value === 'database') {
            $('#multiple_db_table_name_container').slideDown();
            $('#multiple_db_table_value_container').slideDown();
            $('#multiple_db_table_text_container').slideDown();
            if( $('#multiple_with_image').prop('checked') ) {
                $('#multiple_db_table_image_container').slideDown();
            }
            
            $('#multiple_db_foreign_key_container').slideDown();
            $('#multiple_db_plural_container').slideDown();
            $('#multiple_db_singular_container').slideDown();
            
            $('#multiple_custom_data_container').slideUp();
        }
    });
    
    $('#multiple_with_image').change(function() {
        if($(this).prop('checked') === true) {
            $('.multiple-has-image').slideDown();
            if( $('#multiple_data').val() === 'custom') {
                $('#multiple_db_table_image_container').hide();
            }
        } else {
            $('.multiple-has-image').slideUp();
        }
    });
    
    $('#multiple_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#multiple_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });

        if( $('#multiple_form').valid()) {

            var values = $( '#multiple_form' ).serializeJSON();

            var list = $('<li>');
            
            var type = values['type'];
            var label = values['label'];
            var field_name = values['name'];
            var field_id = values['id'];
            var validations = values['validations'];
            
            var required = $.inArray('required', validations) === 1 ? ' data-rule-required="true" ' : ' ';  
            var required_label = $.inArray('required', validations) !== -1 ? ' *' : '';
            
            var data_source = values['multiple_data'];
            var data = values['data'];
            
            var database_name = values['db_table_name'];
            var database_attribute_value = values['db_table_value'];
            var database_attribute_text = values['db_table_text'];
            var database_attribute_image = (values['db_table_image'] !== undefined && values['db_table_image'] !== '') ? values['db_table_image'] : 'none';
            
            var tagsinput = values['default_values'];
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';

            var with_image = $('#multiple_with_image').prop('checked') ? true : false;

            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + required_label+ '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + required_label + '</label>';
            }
            markup += '<div class="controls">';
            
            if(type === 'multiple_dropdown') {
                
                markup += '<select name="' +field_name+ '" id="' +field_id+ '" multiple="multiple" class="chosen-select input-xxlarge">';
                
                if(data_source === 'custom') {
                    $.each(data, function(idx, obj) {
                        
                        var value = (data[idx]['value'] !== undefined) ? ' value="' +data[idx]['value']+ '"' : '';
                        var text = (data[idx]['text'] !== undefined) ? data[idx]['text'] : '';
                        var data_image = (data[idx]['image'] !== undefined) ? data[idx]['image'] : '';
                        
                        if( with_image ) {
                            if( data_image.indexOf('http') != -1 || data_image.indexOf('www') != -1 ) {
                                data_image = ' data-img-src="' + data_image + '"';
                            } else {
                                data_image = ' data-img-src="' + base_url + data_image + '"';
                            }
                        } else {
                            data_image = '';
                        }

                        markup += '<option' + value + data_image + '>' +text+ '</option>';
                        
//                        markup += '<option value="' +data[idx]['value']+ '">' +data[idx]['text']+ '</option>';
                    });
                }
                
                if(data_source === 'database') {
                    var multiple_data = {};
                    multiple_data['db_name'] = database_name;
                    multiple_data['db_attr_value'] = database_attribute_value;
                    multiple_data['db_attr_text'] = database_attribute_text;
                    multiple_data['db_attr_image'] = database_attribute_image;
                    
                    var db_data = get_db_data(base_url + 'generator/retrieve_data', multiple_data);
                    $.each(db_data, function(idx, obj) {
                        var value = (db_data[idx]['value'] !== undefined) ? ' value="' +db_data[idx]['value']+ '"' : '';
                        var text = (db_data[idx]['text'] !== undefined) ? db_data[idx]['text'] : '';
                        var data_image = (db_data[idx]['image'] !== undefined) ? db_data[idx]['image'] : '';
                        if( with_image ) {
                            data_image = ' data-img-src="' + base_url + $('#single_image_path').val() + data_image + '"';
                        } else {
                            data_image = '';
                        }
                        markup += '<option' + value + data_image + '>' +text+ '</option>';
                        
//                        markup += '<option value="' +db_data[idx]['value']+ '">' +db_data[idx]['text']+ '</option>';
                    });
                }
                markup += '</select>';
            }
            
            if(type === 'checkbox') {
                
                if(data_source === 'custom') {
                    $.each(data, function(idx, obj) {
                        markup += '<label class="checkbox"><input type="checkbox" name="' +field_name+ '" value="' +data[idx]['value']+ '">' +data[idx]['text']+ '</label>';
                    });
                }
                
                if(data_source === 'database') {
                    var multi_data = {};
                    multi_data['db_name'] = database_name;
                    multi_data['db_attr_value'] = database_attribute_value;
                    multi_data['db_attr_text'] = database_attribute_text;
                    
                    var multi_db_data = get_db_data(base_url + 'generator/retrieve_data', multi_data);
                    $.each(db_data, function(idx, obj) {
                        markup += '<label class="checkbox"><input type="checkbox" name="' +field_name+ '" value="' +multi_db_data[idx]['value']+ '">' +multi_db_data[idx]['text']+ '</label>';
                    });
                }
            }
            
            if(type === 'tagsinput') {
                markup += '<input type="text" name="' +field_name+ '" id="' +field_id+ '" class="tagsinput" value="' +tagsinput+ '">';
            }
            
            markup += '</div></div>';

            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            if(type === 'multiple_dropdown') {
                $("ul#sortable li:last-child .chosen-select").chosen({});
            }
            
            if(type === 'tagsinput') {
                $("ul#sortable li:last-child .tagsinput").tagsInput({width: "auto", height: "auto"});
            }
            
            // hide modal
            $('#multiple_modal').modal('hide');
        }
    });
    // ------------------- Multiple Button -------------- //
    $('#checkbox_btn').click(function() {
        reset_multiple_form();
        to_multiple_checkbox();
        $('#multiple_type_container').hide();
        $('#multiple_modal').modal({
            width: '95%'
        });
    });
    
    $('#multiple_dropdown_btn').click(function() {
        reset_multiple_form();
        to_multiple_dropdown();
        $('#multiple_type_container').hide();
        $('#multiple_modal').modal({
            width: '95%'
        });
    });
    
    $('#tagsinput_btn').click(function() {
        reset_multiple_form();
        to_multiple_tagsinput();
        $('#multiple_type_container').hide();
        $('#multiple_modal').modal({
            width: '95%'
        });
    });
    
//    -------------------------------------------------------------------------- Captcha
    
    $('#captcha_modal').on('shown', function() {
        $("#captcha_label").focus();
    });

    // auto fill-up captcha name and id
    $('#captcha_label').change(function() {
        var text_label = $(this).val().toLowerCase().replace(/ /g,'_');
        $('#captcha_name').val(text_label);
        $('#captcha_id').val(text_label);
    });
    
    $('#captcha_save_btn').click(function(event) {
        event.preventDefault();
        
        $('#captcha_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });

        if( $('#captcha_form').valid()) {

            var values = $( '#captcha_form' ).serializeJSON();

            var list = $('<li>');
            
            var label = values['label'] !== undefined ? values['label'] : '';
            var field_name = values['name'] !== undefined ? values['name'] : '';
            var field_id = values['id'] !== undefined ? values['id'] : '';
            var placeholder = values['placeholder'] !== undefined ? ' placeholder="' +values['placeholder']+ '"' : '';
            
            var length = values['captcha_length'] !== undefined ? values['captcha_length'] : '6';
            var location = values['location'] !== undefined ? values['location'] : 'uploads/images/captcha';
            var expiration = values['captcha_expiration'] !== undefined ? values['captcha_expiration'] : '900';
            var width = values['captcha_width'] !== undefined ? values['captcha_width'] : '300';
            var height = values['captcha_height'] !== undefined ? values['captcha_height'] : '100';
            
            // guidelines
            var guideline = (values['guideline'] !== undefined && values['guideline'] !== '') ? true : false;
            var guideline_text = (values['guideline'] !== undefined && values['guideline'] !== '') ? values['guideline'] : '';
            
            var use_switch = $('#switch').prop('disabled');
            if( ! use_switch) {
                use_switch = (values['switch'] === 'yes') ? true : false;
            }
            
            var markup = '';
            markup += '<div class="control-group">';
            markup += '<button type="button" class="close" onclick="remove_item(this)">&times;</button>';
            markup += '<label for="' +field_id+ '_image" class="control-label handle">' +label + ' Image' + '</label>';
            markup += '<div class="controls">';
            
            var captcha_data = {};
            captcha_data['length'] = length;
            captcha_data['location'] = location;
            captcha_data['expiration'] = expiration;
            captcha_data['width'] = width;
            captcha_data['height'] = height;
            var captcha = get_data( base_url + 'generator/captcha', captcha_data, 'text' );
            
            markup += '<div id="' +field_id+ '_image">' +captcha+ '</div>';

//            markup += '<input type="checkbox" name="' +field_name+ '" id="' +field_id+ '" class="switch has-switch"' + required + on_text + off_text + placeholder + '>';
            markup += '</div></div>';

            markup += '<div class="control-group">';
            if(guideline) {
                markup += '<label for="' +field_id+ '" class="control-label handle" rel="popover" data-trigger="hover" title="Guideline" data-placement="top" data-content="' +guideline_text+ '">' +label + '*' + '<noscript><small>( ' +guideline_text+  ' )</small></noscript></label>';
            } else {
                markup += '<label for="' +field_id+ '" class="control-label handle">' +label + '*' + '</label>';
            }
            markup += '<div class="controls">';
            markup += '<div class="input-prepend">';
            markup += '<span class="add-on"><i class="icon-camera"></i></span>';
            markup += '<input type="text" name="' +field_name+ '" id="' +field_id+ '" class="input-xlarge" data-rule-required="true" data-rule-minlength="2" data-rule-maxlength="1000"' +placeholder+ '>';
            markup += '</div></div></div>';
            
            // attach object to dom
            list.html(markup);
            list.data('controls', values);
            $('ul#sortable').append(list);
            
            $("#" +field_id+ "_image").click(function(){
                $(this).html( get_data( base_url + 'generator/captcha', captcha_data, 'text' ) );
            });
            
            // reinitialize popovers
            $('body').popover(popover_options);
            
            // hide modal
            $('#captcha_modal').modal('hide');
        }
    });
    // ------------------- Captcha Button -------------- //
    $('#generic_captcha_btn').click(function() {
        reset_captcha_form();
        $('#captcha_modal').modal({
            width: '95%'
        });
    });
    
    $('#captcha_btn').click(function() {
        reset_captcha_form();
        to_switch();
        $('#captcha_modal').modal({
            width: '95%'
        });
    });
    
    
// ----------------------------------------------------------------------------- General

    $('#form_guideline').keyup(function() {
       $('#wysiwyg_form_guideline').html( $(this).val() ); 
    });
    
    $('#status_type').change(function(){
       if( $('#status_type').val() === 'custom' ) {
           
           $('#custom_active_container').slideDown();
           $('#custom_inactive_container').slideDown();
           $('#custom_archived_container').slideDown();
           
       } else {
           
           $('#custom_active_container').slideUp();
           $('#custom_inactive_container').slideUp();
           $('#custom_archived_container').slideUp();
       }
    });



// ----------------------------------------------------------------------------- Generate
    
    $('#btn_save').click(function(e) {
        e.preventDefault();
        
        $('#form_form').submit(function() {
            // always return false, we are not submitting to the server
            return false;
        });
        
        if( $('#form_form').valid()) {
            
            var data = {};
            var fields = Array();

            $('ul#sortable li').each(function(i) {
                fields.push( $(this).data('controls') );
            });

    //        var my_data = $('ul#sortable li:last-child').data('controls');
    //        alert(my_data['data_type']);

            data['singular'] = $('#content_singular_name').val().toLowerCase();
            data['singular_underscore'] = $('#content_singular_name').val().toLowerCase().replace(/ /g,'_');
            data['singular_capital'] = $('#content_singular_name').val().toLowerCase().replace(/\b[a-z]/g, function(letter) {return letter.toUpperCase();});
            data['singular_capital_underscore'] = $('#content_singular_name').val().toLowerCase().replace(/\b[a-z]/g, function(letter) {return letter.toUpperCase();}).replace(/ /g,'_');
            
            data['plural'] = $('#content_plural_name').val().toLowerCase();
            data['plural_underscore'] = $('#content_plural_name').val().toLowerCase().replace(/ /g,'_');
            data['plural_capital'] = $('#content_plural_name').val().toLowerCase().replace(/\b[a-z]/g, function(letter) {return letter.toUpperCase();});
            data['plural_capital_underscore'] = $('#content_plural_name').val().toLowerCase().replace(/\b[a-z]/g, function(letter) {return letter.toUpperCase();}).replace(/ /g,'_');
            
            data['singular_dash'] = $('#content_singular_name').val().toLowerCase().replace(/ /g,'-');
            data['singular_capital_dash'] = $('#content_singular_name').val().toLowerCase().replace(/\b[a-z]/g, function(letter) {return letter.toUpperCase();}).replace(/ /g,'-');
            
            data['plural_dash'] = $('#content_plural_name').val().toLowerCase().replace(/ /g,'-');
            data['plural_capital_dash'] = $('#content_plural_name').val().toLowerCase().replace(/\b[a-z]/g, function(letter) {return letter.toUpperCase();}).replace(/ /g,'-');
            
            data['has_gallery'] = $('#has_gallery').is(':checked') ? 'yes' : 'no';
            
            data['status'] = $('#status_type').val();
            data['custom_active'] = $('#custom_active').val();
            data['custom_inactive'] = $('#custom_inactive').val();
            data['custom_archived'] = $('#custom_archived').val();
            
            data['database_name'] = $('#database_name').val();
            data['database_prefix'] = $('#database_prefix').val();
            data['form_guideline'] = $('#form_guideline').val();
            
            data['fields'] = fields;

            send_data(base_url + 'generator/generate', data);
        }
        
        
    });
});

function send_data(url, data) {
    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'text',
        data: data,
        success: function(res) {
            alert(res);
//            document.location = base_url + 'generator/download/action/' + data['singular_underscore'];
        }
    });
}

function get_db_data(url, data)
{
    var db_data;
    $.ajax({
        type: 'POST',
        url: url,
        dataType: 'json',
        data: data,
        async: false,
        success: function(res) {
            db_data = res;
        }
    });
    return db_data;
}

function get_data(url, data, format)
{
    var data;
    $.ajax({
        type: 'POST',
        url: url,
        dataType: format,
        data: data,
        async: false,
        success: function(res) {
            data = res;
        }
    });
    return data;
}

//$('document').ready(function() {
//    initialize_map('map_canvas', 'longitude', 'latitude', '16.413640135538014', '120.61758366806225');
//});

